<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset='utf-8'>
	<title>Parsec Web Client</title>
	<link rel="stylesheet" href="style.css">
</head>

<body>
	<div class="video-container">
		<video></video>
	</div>

	<table id='server-list'></table>

	<script type='module'>
		import * as API from './api.js';
		import {Client} from './client.js';


		/*** CLIENT ***/
		function toggleFullscreen(element) {
			if (document.webkitFullscreenElement) {
				document.webkitExitFullscreen();

			} else {
				element.webkitRequestFullscreen();

				if (navigator.keyboard && navigator.keyboard.lock)
					navigator.keyboard.lock();
			}
		}

		function runClient(element, sessionId, serverId) {
			return new Promise((resolve) => {
				//set up client object with an event callback: gets connect, status, chat, and shutter events
				const client = new Client(element, (event) => {
					console.log('EVENT', event);

					if (event.type === 'exit') {
						document.removeEventListener('keydown', hotkeys, true);
						resolve(event.code);
					}
				});

				//set up useful hotkeys that call client methods: destroy can also be used to cancel pending connection
				const hotkeys = (event) => {
					event.preventDefault();

					if (event.code === 'Backquote' && event.ctrlKey && event.altKey) {
						client.destroy(0);

					} else if (event.code === 'KeyW' && event.ctrlKey && event.altKey) {
						toggleFullscreen(element);
					}
				};
				document.addEventListener('keydown', hotkeys, true);

				client.connect(sessionId, serverId, {
					encoder_bitrate: 12,
				});
			});
		}


		/*** UI HELPERS ***/
		function addRow(table) {
			const tr = document.createElement('tr');
			table.appendChild(tr);
			return tr;
		}

		function addTextCol(tr, text) {
			const td = document.createElement('td');
			td.textContent = text;
			tr.appendChild(td);
		}

		function addButtonCol(tr, text, onclick) {
			const td = document.createElement('td');
			tr.appendChild(td);

			const button = document.createElement('button');
			button.textContent = text;
			button.onclick = onclick;
			td.appendChild(button);
		}

		function addInputCol(tr, id, type, onenter) {
			const td = document.createElement('td');
			tr.appendChild(td);

			const input = document.createElement('input');
			input.id = id;
			input.type = type;
			input.onkeyup = (event) => {
				if (event.keyCode === 13)
					onenter();
			};
			td.appendChild(input);
		}


		/*** MAIN ***/
		async function serverTable(sessionId) {
			const json = await API.serverList(sessionId);
			const table = document.querySelector('#server-list');

			for (const server of json) {
				const tr = addRow(table);
				addTextCol(tr, server.name);
				addTextCol(tr, server.build);
				addTextCol(tr, server.server_id);
				addTextCol(tr, server.status);
				addButtonCol(tr, 'Connect', async () => {
					const container = document.querySelector('.video-container');
					const element = document.querySelector('video');

					table.style.display = 'none';
					container.style.display = 'block';

					const code = await runClient(element, sessionId, server.server_id);

					table.style.display = '';
					container.style.display = '';

					element.src = '';
					element.load();

					if (code !== 0)
						alert(`Exit code: ${code}`);
				});
			}

			const tr = addRow(table);
			addButtonCol(tr, 'Logout', () => {
				delete sessionStorage.sessionId;
				window.location.reload();
			});
		}

		function authTable() {
			async function submit() {
				const email = document.querySelector('#email').value;
				const password = document.querySelector('#password').value;

				const json = await API.auth(email, password);
				sessionStorage.sessionId = json.session_id;
				window.location.reload();
			}

			const table = document.querySelector('#server-list');

			let tr = addRow(table);
			addTextCol(tr, 'Email');
			addInputCol(tr, 'email', 'email', submit);

			tr = addRow(table);
			addTextCol(tr, 'Password');
			addInputCol(tr, 'password', 'password', submit);

			document.querySelector('#email').focus();
		}

		if (!sessionStorage.sessionId) {
			authTable();

		} else {
			serverTable(sessionStorage.sessionId);
		}
	</script>
</body>

</html>
